package com.sky.service.user.impl;

import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper;
import com.sky.constant.MessageConstant;
import com.sky.context.BaseContext;
import com.sky.controller.user.WxPayController;
import com.sky.dto.OrdersPageQueryDTO;
import com.sky.exception.OrderBusinessException;
import com.sky.mapper.user.OrderDetailMapper;
import com.sky.mapper.user.UserOrderMapper;
import com.sky.mapper.user.ShoppingCartMapper;
import com.sky.mapper.user.UserHistoryOrdersMapper;
import com.sky.pojo.OrderDetail;
import com.sky.pojo.Orders;
import com.sky.pojo.ShoppingCart;
import com.sky.result.PageResult;
import com.sky.service.user.UserHistoryOrdersService;
import com.sky.vo.OrderVO;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.time.LocalDateTime;
import java.util.List;

@Service
@Slf4j
public class UserHistoryOrdersServiceImpl implements UserHistoryOrdersService {
    @Autowired
    private UserHistoryOrdersMapper userHistoryOrdersMapper;
    @Autowired
    private OrderDetailMapper orderDetailMapper;
    @Autowired
    private ShoppingCartMapper shoppingCartMapper;
    @Autowired
    private WxPayController wxPayController;
    @Autowired
    private UserOrderMapper userOrderMapper;

    /**
     * 历史订单
     * @param param
     * @return
     */
    @Override
    public PageResult historyOrders(OrdersPageQueryDTO param) {
        log.info("service层历史订单:{}",param);
        param.setUserId(BaseContext.getCurrentId());
        PageHelper.startPage(param.getPage(), param.getPageSize());
        Page<OrderVO> page =userHistoryOrdersMapper.historyOrders(param);
        for (OrderVO orderVO : page) {
            Long id = orderVO.getId();
            List<OrderDetail> orderDetails=orderDetailMapper.selectByOrderId(id);
            orderVO.setOrderDetailList(orderDetails);
        }
        return new PageResult(page.getTotal(), page.getResult());
    }

    /**
     * 历史订单详情
     * @param
     * @return
     */
    @Override
    public OrderVO getById(Long id) {
        log.info("service层历史订单详情:{}",id);
      OrderVO orderVO = userHistoryOrdersMapper.getById(id);
      List<OrderDetail> orderDetails=orderDetailMapper.selectByOrderId(id);
      orderVO.setOrderDetailList(orderDetails);
      return orderVO;
    }

    /**
     * 取消订单
     * @param id
     */
    @Override
    public void cancel(Long id) {
        log.info("取消订单:{}",id);
        OrderVO orderVO = userHistoryOrdersMapper.getById(id);
        //校验订单是否存在
        if (orderVO==null){
            throw new OrderBusinessException(MessageConstant.ORDER_NOT_FOUND);
        }
            Integer status = orderVO.getStatus();
        if (status>2){
            throw new OrderBusinessException(MessageConstant.ORDER_STATUS_ERROR);
        }
        Orders orders = new Orders();
        orders.setId(orderVO.getId());
        //待接单状态下取消，需要退款
        if (orderVO.getStatus().equals(Orders.TO_BE_CONFIRMED)){
            //调用微信支付退款接口
            wxPayController.refund();
            //更改支付状态为退款
            orders.setPayStatus(Orders.REFUND);
        }
        //补充数据，更新订单状态
        orders.setStatus(Orders.CANCELLED_ORDER);
        orders.setCancelReason("用户取消");
        orders.setCancelTime(LocalDateTime.now());
        userOrderMapper.updateOrderPaySuccess(orders);
        }


    /**
     * 再来一单
     * @param id
     */
    @Override
    public void repetition(Long id) {
        log.info("再来一单:{}",id);
        List<OrderDetail> orderDetails = orderDetailMapper.selectByOrderId(id);
        Long userId = BaseContext.getCurrentId();

        //方法一：
        for (OrderDetail orderDetail : orderDetails) {
            ShoppingCart shoppingCart = new ShoppingCart();
            shoppingCart.setUserId(userId);
            shoppingCart.setName(orderDetail.getName());
            shoppingCart.setImage(orderDetail.getImage());
            shoppingCart.setAmount(orderDetail.getAmount());
            shoppingCart.setDishFlavor(orderDetail.getDishFlavor());
            shoppingCart.setDishId(orderDetail.getDishId());
            shoppingCart.setSetmealId(orderDetail.getSetmealId());
            shoppingCart.setNumber(orderDetail.getNumber());
            shoppingCartMapper.add(shoppingCart);
        }
        /*方法二：
        List<ShoppingCart> shoppingCartList=orderDetails.stream().map(orderDetail -> {
            ShoppingCart shoppingCart = new ShoppingCart();
            BeanUtils.copyProperties(orderDetail, shoppingCart);
            shoppingCart.setUserId(userId);
            shoppingCart.setCreateTime(LocalDateTime.now());
            return shoppingCart;
        }).collect(Collectors.toList());
        shoppingCartMapper.insertBatch(shoppingCartList);*/
    }
}
